package com.qigao.mall.channel.alipay;

import com.alibaba.fastjson.JSONObject;
import com.qigao.mall.channel.ChannelCore;
import com.qigao.mall.channel.config.ChannelConstant;
import com.qigao.mall.commons.dto.MerChannelDto;
import com.qigao.mall.commons.enums.*;
import com.qigao.mall.commons.param.ChannelReqParam;
import com.qigao.mall.commons.param.ChannelRespParam;
import com.qigao.mall.commons.utils.DateUtil;
import com.qigao.mall.commons.utils.PairString;
import com.qigao.mall.commons.utils.RSAUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:luiz
 * @Date: 2018/5/28 11:16
 * @Descripton:支付宝手机网站支付
 * @Modify :https://docs.open.alipay.com/203/107090
 **/
@Service
public class AliPayWapPay implements ChannelCore {
    private static final Logger logger= LoggerFactory.getLogger(AliPayWapPay.class);

    @Resource
    ChannelConstant channelConstant;


    @Override
    public boolean isSupport(PayProductEnum payProductEnum, ChannelActionEnum channelActionEnum, ChannelInfoEnum channelInfoEnum) {
        return ChannelActionEnum.CREATE_ORDER.equals(channelActionEnum) && PayProductEnum.ALIPAY_WAP_WEB.equals(channelInfoEnum);
    }

    @Override
    public ChannelRespParam channelProcess(MerChannelDto merChannelDto, ChannelReqParam channelReqParam) {
        //1.构造请求参数
        String reqContent=buildReqParam(merChannelDto,channelReqParam);
        logger.info("[支付宝手机网站支付]返回内容:{}",reqContent);
        ChannelRespParam channelRespParam=new ChannelRespParam();
        channelRespParam.setRespCode(ChannelCodeEnum.SUCCESS.getCode());
        channelRespParam.setRespMsg("成功");
        channelRespParam.setFormatEnum(StreamFormatEnum.STREAM);
        channelRespParam.setRespContent(reqContent);
        //3.处理响应
        return channelRespParam;
    }

    private String buildReqParam(MerChannelDto merChannelDto, ChannelReqParam channelReqParam) {
        Map reqParam=new ConcurrentHashMap<>();
        reqParam.put("app_id", merChannelDto.getAppId());
        reqParam.put("method","alipay.trade.wap.pay");
        reqParam.put("format","json");
        reqParam.put("charset","UTF-8");
        reqParam.put("timestamp", DateUtil.getDateTimeFormat(new Date()));
        reqParam.put("version","1.0");
        reqParam.put("notify_url",channelConstant.getAlipayNotifyUrl());
        reqParam.put("return_url",channelConstant.getForwardUrl());
        reqParam.put("sign_type", "RSA2");

        JSONObject bizContent=new JSONObject();
        bizContent.put("out_trade_no", merChannelDto.getInnerSeqNo());
        bizContent.put("product_code","QUICK_WAP_WAY");
        JSONObject reqContent= JSONObject.parseObject(channelReqParam.getReqContent());
        bizContent.put("body",reqContent.getString("goodsName"));
        bizContent.put("subject",reqContent.getString("goodsName"));
        bizContent.put("total_amount",reqContent.getString("payAmt"));
        reqParam.put("biz_content",bizContent.toString());
        String content=  PairString.createLinkString(reqParam);
        logger.info("待签名的内容:{}",content);
        String signValue= RSAUtils.signWithRsa2(content, merChannelDto.getPrivKey());
        reqParam.put("sign",signValue);
        logger.info("签名:{}",signValue);

        reqParam.remove("biz_content");
        String baseUrl=PairString.createLinkStringForEncode(reqParam);
        baseUrl=channelConstant.getAlipayUrl()+"?"+baseUrl;
        //转义后给前端显示
       // String parameterContent=StringHtmlUtils.htmlEncode(bizContent.toString());
        return buildForm(baseUrl,bizContent);
    }


    public static String buildForm(String baseUrl, JSONObject bizContent) {
        StringBuffer sb = new StringBuffer();
        sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
        sb.append("<html>");
        sb.append("<head>");
        sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
        sb.append("<title>付款</title>");
        sb.append("</head>");
        sb.append("<form name=\"punchout_form\" method=\"post\" action=\"");
        sb.append(baseUrl);
        sb.append("\">\n");
        sb.append(buildHiddenField(bizContent));
        sb.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >\n");
        sb.append("</form>\n");
        sb.append("<script>document.forms[0].submit();</script>");
        sb.append("</html>");
        String form = sb.toString();
        return form;
    }

    private static String buildHiddenField( JSONObject bizContent) {
        StringBuffer sb = new StringBuffer();
        sb.append("<input type=\"hidden\" name=\"");
        sb.append("biz_content");
        sb.append("\" value=\"");
        //转义双引号
       String a = bizContent.toString().replace("\"", "&quot;");
        sb.append(a).append("\">\n");
        return sb.toString();
    }



}
